package product

import (
	"context"
	"errors"
	"group-buy/group_buy/internal/models"

	"group-buy/group_buy/internal/svc"
	"group-buy/group_buy/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveProductDivisionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSaveProductDivisionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveProductDivisionLogic {
	return &SaveProductDivisionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SaveProductDivisionLogic) SaveProductDivision(req *types.ProductDivision) (resp *types.ProductDivision, err error) {

	amount := req.DealerAmount + req.InviteParentAmount + req.InviteAmount + req.BusinessAmount

	product := &models.Product{Id: req.ProductId}
	get, err := l.svcCtx.Engine.Get(product)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取产品失败")
	}

	if product.Price*0.9 < amount {
		return nil, errors.New("分账总额应不超过商品价格的90%")
	}

	business := &models.Business{Id: product.BusinessId}
	get, err = l.svcCtx.Engine.Get(business)
	if err != nil {
		return nil, err
	}
	if !get {
		return nil, errors.New("获取门店失败")
	}

	m := &models.ProductDivision{
		Id:                 req.Id,
		ProductName:        product.Name,
		ProductId:          req.ProductId,
		InviteAmount:       req.InviteAmount,
		InviteParentAmount: req.InviteParentAmount,
		BusinessAmount:     req.BusinessAmount,
		DealerAmount:       req.DealerAmount,
	}
	if m.BusinessAmount > 0 && business.UserId <= 0 {
		return nil, errors.New("门店未绑定用户")
	}
	if m.DealerAmount > 0 && business.DealerId <= 0 {
		return nil, errors.New("门店未绑定经销商")
	}

	if m.Id > 0 {
		_, err = l.svcCtx.Engine.ID(m.Id).MustCols("invite_amount", "invite_parent_amount", "business_amount", "dealer_amount").Update(m)
		if err != nil {
			return nil, err
		}
	} else {
		exist, err := l.svcCtx.Engine.Exist(&models.ProductDivision{ProductId: m.ProductId})
		if err != nil {
			return nil, err
		}
		if exist {
			_, err := l.svcCtx.Engine.Where("product_id=?", m.ProductId).Update(m)
			if err != nil {
				return nil, err
			}
		}
		_, err = l.svcCtx.Engine.Insert(m)
		if err != nil {
			return nil, err
		}
	}
	req.Id = m.Id
	return req, nil
}
